package com.stox.shared.indicator.model;

import com.stox.shared.indicator.model.config.BaseIndicatorConfig;
import com.stox.shared.indicator.model.enumeration.IndicatorDisplayType;
import com.stox.shared.indicator.model.enumeration.IndicatorPosition;

public class SimpleMovingAverage extends AbstractIndicator<Double, BaseIndicatorConfig> {

	public static final SimpleMovingAverage INSTANCE = new SimpleMovingAverage();
	
	private SimpleMovingAverage() {
		super("SMA");
	}

	@Override
	public IndicatorDisplayType getDisplayType(final BaseIndicatorConfig config) {
		return IndicatorPosition.INDEPENDENT.equals(getPosition(config)) ? IndicatorDisplayType.AREA : IndicatorDisplayType.LINE;
	}

	@Override
	public IndicatorPosition getPosition(final BaseIndicatorConfig config) {
		switch (config.getBarValue()) {
			case VOLUME:
				return IndicatorPosition.OVERLAY_VOLUME;
			case RANGE:
				return IndicatorPosition.INDEPENDENT;
			default:
				return IndicatorPosition.OVERLAY_PRICE;
		}
	}

	@Override
	public Double getValue(final BaseIndicatorConfig configuration, final Double[] in, final int index) throws UnsupportedOperationException {
		double sum = 0;
		final int span = configuration.getSpan();
		for (int i = index; i < (index + span); i++) {
			sum += in[index];
		}
		return sum / span;
	}

	@Override
	public Double[] getValues(final BaseIndicatorConfig configuration, final Double[] values) throws UnsupportedOperationException {
		final Double[] result = new Double[values.length];
		double sum = 0;
		final int span = configuration.getSpan();
		final int size = values.length;
		for (int i = size - 1; i >= 0; i--) {
			if (null == values[i]) {
				continue;
			}
			sum += values[i];
			if (i > (size - 1 - span)) {
				continue;
			}
			if (null == values[i + span]) {
				continue;
			}
			sum -= values[i + span];
			result[i] = sum / span;
		}
		return result;
	}

	@Override
	public BaseIndicatorConfig createDefaultConfiguration() {
		return new BaseIndicatorConfig();
	}

}
